<template>
    <div class="main-container">
        <global />
        <div class="main-content">
            <div class="content-container">
                <div class="service-manage">
                    <div class="header">
                        <!-- 新增搜索和筛选组件 -->
                        <el-input v-model="sSid" placeholder="请输入学生学号"
                            style="width: 200px; margin-right: 10px;"></el-input>
                        <el-select v-model="sGrade" placeholder="选择年级" style="width: 150px; margin-right: 10px;"
                            clearable @change="pageChange">
                            <el-option v-for="grade in gradeOptions" :key="grade" :value="grade"></el-option>
                        </el-select>
                        <el-select v-model="sSpecialized" placeholder="选择专业" style="width: 150px; margin-right: 10px;"
                            clearable @change="pageChange">
                            <el-option v-for="major in majorOptions" :key="major" :value="major"></el-option>
                        </el-select>
                        <el-button type="primary" @click="pageChange">搜索</el-button>
                        <el-button type="primary" style="margin-left: 10px;" @click="addstudent">新增学生</el-button>
                        <!-- 新增批量添加按钮 -->
                        <el-button type="primary" style="margin-left: 10px;"
                            @click="openBatchAddDialog">批量添加</el-button>
                    </div>

                    <!-- 新增批量添加学生弹窗 -->
                    <el-dialog v-model="batchAddDialogVisible" title="批量添加学生" width="60%">
                        <el-upload class="upload-demo" action="#" :auto-upload="false" @change="handleBatchExcelUpload"
                            accept=".xlsx,.xls">
                            <el-button type="primary">上传 Excel</el-button>
                            <h3>请按照学号、密码、姓名、专业、年级、班级格式填写Excel文件</h3>
                        </el-upload>
                        <!-- 确保这里的 :data 绑定正确 -->
                        <el-table v-if="batchExcelData.length" :data="batchExcelData" border style="width: 100%">
                            <el-table-column prop="ssid" label="学号"></el-table-column>
                            <el-table-column prop="spassword" label="密码"></el-table-column>
                            <el-table-column prop="sname" label="姓名"></el-table-column>
                            <el-table-column prop="sspecialized" label="专业"></el-table-column>
                            <el-table-column prop="sgrade" label="年级"></el-table-column>
                            <el-table-column prop="sclass" label="班级"></el-table-column>
                            <el-table-column prop="smgrades" label="入学成绩"></el-table-column>
                        </el-table>
                        <template #footer="scope">
                            <el-button @click="batchAddDialogVisible = false">取消</el-button>
                            <el-button type="primary" @click="addlist">确定</el-button>
                        </template>
                    </el-dialog>

                    <!-- 编辑/新增学生弹窗 -->
                    <el-dialog v-model="dialogVisible" :title="text" width="40%">
                        <el-form :model="studentForm" label-width="100px">
                            <el-row :gutter="20">
                                <el-col :span="12">
                                    <el-form-item label="学生学号">
                                        <el-input v-if="text == '新增学生'" v-model="studentForm.sSid" placeholder="请输入学生学号"></el-input>
                                        <el-input v-if="text == '编辑学生'" v-model="studentForm.sSid" placeholder="请输入学生学号" disabled></el-input>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="12">
                                    <el-form-item label="学生密码">
                                        <el-input v-model="studentForm.sPassword" placeholder="请输入学生密码"
                                            v-if="text == '新增学生'"></el-input>
                                        <el-input v-model="studentForm.sPassword" placeholder="默认密码不显示，如修改请输入"
                                            v-if="text == '编辑学生'"></el-input>
                                    </el-form-item>
                                </el-col>
                            </el-row>
                            <el-row :gutter="20">
                                <el-col :span="12">
                                    <el-form-item label="学生姓名">
                                        <el-input v-model="studentForm.sName" placeholder="请输入学生姓名" v-if="text == '新增学生'"></el-input>
                                        <el-input v-model="studentForm.sName" placeholder="请输入学生姓名" v-if="text == '编辑学生'" disabled></el-input>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="12">
                                    <el-form-item label="联系电话">
                                        <el-input v-model="studentForm.sPhone" placeholder="请输入联系电话（选填）" v-if="text == '编辑学生'"></el-input>
                                    </el-form-item>
                                </el-col>
                            </el-row>
                            <el-row :gutter="20">
                                <el-col :span="12">
                                    <el-form-item label="学生年级">
                                        <el-select v-model="studentForm.sGrade" placeholder="选择或输入年级" filterable allow-create
                                            default-first-option style="width: 100%" v-if="text == '新增学生'">
                                            <el-option v-for="item in gradeOptions" :key="item" :label="item" :value="item" />
                                        </el-select>
                                        <el-input v-model="studentForm.sGrade" placeholder="请输入学生年级" v-if="text == '编辑学生'" disabled></el-input>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="12">
                                    <el-form-item label="学生专业">
                                        <el-select v-model="studentForm.sSpecialized" placeholder="选择或输入专业" filterable
                                            allow-create default-first-option style="width: 100%" v-if="text == '新增学生'">
                                            <el-option v-for="item in majorOptions" :key="item" :label="item" :value="item" />
                                        </el-select>
                                        <el-input v-model="studentForm.sSpecialized" placeholder="请输入学生专业" v-if="text == '编辑学生'" disabled></el-input>
                                    </el-form-item>
                                </el-col>
                            </el-row>
                            <el-row :gutter="20">
                                <el-col :span="12">
                                    <el-form-item label="学生班级">
                                        <el-input v-model="studentForm.sClass" placeholder="请输入学生班级" v-if="text == '新增学生'"></el-input>
                                        <el-input v-model="studentForm.sClass" placeholder="请输入学生班级" v-if="text == '编辑学生'" disabled></el-input>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="12">
                                    <el-form-item label="电子邮箱">
                                        <el-input v-if="text == '编辑学生'" v-model="studentForm.sEmail" placeholder="请输入电子邮箱（选填）"></el-input>
                                    </el-form-item>
                                </el-col>
                            </el-row>
                            <el-row :gutter="20">
                                <el-col :span="12">
                                    <el-form-item label="出生日期">
                                        <el-date-picker
                                            v-model="studentForm.sBirthday"
                                            type="date"
                                            placeholder="选择出生日期（选填）"
                                            style="width: 100%"
                                            value-format="YYYY-MM-DD"
                                            v-if="text == '编辑学生'"
                                        />
                                    </el-form-item>
                                </el-col>
                                <el-col :span="12">
                                    <el-form-item label="监护人姓名">
                                        <el-input v-if="text == '编辑学生'" v-model="studentForm.sPname" placeholder="请输入监护人姓名（选填）"></el-input>
                                    </el-form-item>
                                </el-col>
                            </el-row>
                            <el-row :gutter="20">
                                <el-col :span="12">
                                    <el-form-item label="入学成绩">
                                        <el-input v-model="studentForm.sMgrades" placeholder="请输入入学成绩" v-if="text == '新增学生'"></el-input>
                                        <el-input v-model="studentForm.sMgrades" placeholder="请输入入学成绩" v-if="text == '编辑学生'" disabled></el-input>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="12">
                                    <el-form-item label="家庭住址">
                                        <el-input v-if="text == '编辑学生'" v-model="studentForm.sAddress" placeholder="请输入家庭住址（选填）"></el-input>
                                    </el-form-item>
                                </el-col>
                            </el-row>
                        </el-form>
                        <template #footer="scope">
                            <el-button @click="dialogVisible = false">取消</el-button>
                            <el-button type="primary" @click="add" v-if="text == '新增学生'">确定</el-button>
                            <el-button type="primary" @click="updateStu" v-if="text == '编辑学生'">保存</el-button>
                        </template>
                    </el-dialog>

                    <el-table :data="students" border style="width: 100%">
                        <el-table-column type="expand">
                            <template #default="props">
                                <div class="student-detail-expand">
                                    <el-descriptions :column="2" border>
                                        <el-descriptions-item label="出生日期">
                                            {{ props.row.sBirthday || '暂无' }}
                                        </el-descriptions-item>
                                        <el-descriptions-item label="电子邮箱">
                                            {{ props.row.sEmail || '暂无' }}
                                        </el-descriptions-item>
                                        <el-descriptions-item label="联系电话">
                                            {{ props.row.sPhone || '暂无' }}
                                        </el-descriptions-item>
                                        <el-descriptions-item label="监护人姓名">
                                            {{ props.row.sPname || '暂无' }}
                                        </el-descriptions-item>
                                        <el-descriptions-item label="入学成绩">
                                            {{ props.row.sMgrades || '暂无' }}
                                        </el-descriptions-item>
                                        <el-descriptions-item label="家庭住址">
                                            {{ props.row.sAddress || '暂无' }}
                                        </el-descriptions-item>
                                    </el-descriptions>
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column label="学生学号" prop="sSid"></el-table-column>
                        <el-table-column label="学生姓名" prop="sName"></el-table-column>
                        <el-table-column label="学生专业" prop="sSpecialized"></el-table-column>
                        <el-table-column label="学生年级" prop="sGrade"></el-table-column>
                        <el-table-column label="学生班级" prop="sClass"></el-table-column>
                        <el-table-column label="操作">
                            <template #default="scope">
                                <el-button size="small" @click="editstudent(scope.row)">编辑</el-button>
                            </template>
                        </el-table-column>
                    </el-table>

                    <!-- 分页组件 -->
                    <div class="pagination-container">
                        <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize"
                            :page-sizes="[10, 20, 50, 100]" background layout="total, sizes, prev, pager, next, jumper"
                            :total="total" class="pagination" @change="pageChange" />
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>
<script>
import { reactive, toRefs, computed } from 'vue';
import axios from '../router/axios';
import * as XLSX from 'xlsx';
import { ElMessage } from 'element-plus';

export default {
    setup() {
        const state = reactive({
            gradeOptions: [],
            majorOptions: [],
            batchAddDialogVisible: false,
            batchExcelData: [],
            students: [],
            studentForm: {
                sSid: '',
                sPassword: '',
                sName: '',
                sSpecialized: '',
                sGrade: '',
                sClass: '',
                sPhone: '',
                sEmail: '',
                sBirthday: '',
                sPname: '',
                sMgrades: '',
                sAddress: ''
            },
            currentPage: 1,
            pageSize: 10,
            total: 1000,
            dialogVisible: false,
            text: '',
            sSid: '',
            sGrade: '',
            sSpecialized: ''
        });

        function pageChange() {
            axios.get('api/teacher/student/getStuList', {
                params: {
                    page: state.currentPage,
                    pageSize: state.pageSize,
                    SSid: state.sSid,
                    SGrade: state.sGrade,
                    sSpecialized: state.sSpecialized
                }
            }).then(res => {
                const result = res.data;
                console.log(result)
                if (result.code == 1) {
                    state.students = result.data.records;
                    state.total = result.data.total;
                } else {
                    alert(result.msg);
                }
            })
            // 搜索逻辑已在 computed 属性中实现
        };

        const openAddDialog = () => {
            state.dialogVisible = true;
        };

        const submitForm = () => {
            // 提交新增学生信息
            state.students.push({ ...state.studentForm, id: String(Date.now()) });
            state.dialogVisible = false;
            state.studentForm = {
                name: '',
                introduction: '',
                image: '',
                class: '',
                score: 0,
                duration: 0,
                status: 0,
                grade: '',
                major: ''
            };
        };

        function handleBatchExcelUpload(file) {
            console.log("file:");
            if (!file || !file.raw) {
                console.error('未选择有效的文件');
                return;
            }
            const validTypes = ['application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'application/vnd.ms-excel'];
            if (!validTypes.includes(file.raw.type)) {
                console.error('请上传 Excel 文件');
                return;
            }

            const reader = new FileReader();
            reader.onload = function (e) {
                const data = new Uint8Array(e.target.result);
                const workbook = XLSX.read(data, { type: 'array' });
                const sheetName = workbook.SheetNames[0];
                const worksheet = workbook.Sheets[sheetName];
                let jsonData = XLSX.utils.sheet_to_json(worksheet);

                // 映射 Excel 标题到所需的 prop 属性
                jsonData = jsonData.map(item => {
                    return {
                        ssid: item['学号'],
                        spassword: item['密码'],
                        sname: item['姓名'],
                        sspecialized: item['专业'],
                        sgrade: item['年级'],
                        sclass: item['班级'],
                        smgrades: item['入学成绩']
                    };
                });

                console.log('解析后的 Excel 数据:', jsonData);
                state.batchExcelData = jsonData;
            };

            reader.onerror = function () {
                console.error('文件读取失败');
                alert('文件读取失败，请重试。');
            };

            reader.readAsArrayBuffer(file.raw);
        }
        function addstudent() {
            state.dialogVisible = true;
            state.text = '新增学生';
            state.studentForm = {
                sSid: '',
                sPassword: '',
                sName: '',
                sSpecialized: '',
                sGrade: '',
                sClass: '',
                sPhone: '',
                sEmail: '',
                sBirthday: '',
                sPname: '',
                sMgrades: '',
                sAddresss: ''
            };
        }
        function add() {
            if(state.studentForm.sSid == '' || state.studentForm.sPassword == '' || state.studentForm.sName == '' 
            || state.studentForm.sSpecialized == '' || state.studentForm.sGrade == '' || state.studentForm.sClass == ''
            || state.studentForm.sMgrades == ''){
                ElMessage.warning('请填写完整');
                return;
            }
            // 构建符合要求的数据格式
            const studentData = [{
                sclass: state.studentForm.sClass,
                sgrade: state.studentForm.sGrade,
                sname: state.studentForm.sName,
                spassword: state.studentForm.sPassword,
                ssid: state.studentForm.sSid,
                sspecialized: state.studentForm.sSpecialized
            }];

            axios.post('api/teacher/student/addstu', studentData)
                .then(res => {
                    const result = res.data;
                    if (result.code === 1) {
                        ElMessage.success('添加成功');
                        state.dialogVisible = false;
                        pageChange(); // 刷新列表
                    } else {
                        ElMessage.error(result.msg || '添加失败');
                    }
                })
                .catch(error => {
                    ElMessage.error('操作失败：' + error.message);
                });
        }
        function addlist() {
            console.log(state.batchExcelData)
            axios.post('api/teacher/student/addstu', state.batchExcelData).then(res => {
                const result = res.data;
                console.log(result)
                if (result.code == 1) {
                    ElMessage.success('添加成功');
                    state.batchAddDialogVisible = false;
                    pageChange(); // 刷新列表
                } else {
                    alert(result.msg);
                }
            })
        }
        function editstudent(row) {
            state.dialogVisible = true;
            state.text = '编辑学生'
            state.studentForm = {
                sSid: row.sSid,
                sPassword: '',
                sName: row.sName,
                sSpecialized: row.sSpecialized,
                sGrade: row.sGrade,
                sClass: row.sClass,
                sPhone: row.sPhone || '',
                sEmail: row.sEmail || '',
                sBirthday: row.sBirthday || '',
                sPname: row.sPname || '',
                sMgrades: row.sMgrades || '',
                sAddress: row.sAddress || ''
            };
        }
        function openBatchAddDialog() {
            state.batchAddDialogVisible = true;
        }
        function getGradeAndM() {
            axios.get('api/teacher/student/getGradeAndSpecialty').then(res => {
                const result = res.data;
                console.log(result)
                if (result.code == 1) {
                    state.gradeOptions = result.data.grade;
                    state.majorOptions = result.data.major;
                } else {
                    alert(result.msg);
                }
            })
        }
        function updateStu(){
            if(state.studentForm.sSid == '' || state.studentForm.sName == '' 
            || state.studentForm.sSpecialized == '' || state.studentForm.sGrade == '' || state.studentForm.sClass == ''
            || state.studentForm.sMgrades == ''){
                ElMessage.warning('请填写完整');
                return;
            }
            axios.put('api/teacher/student/updateStu',state.studentForm).then(res =>{
                const result = res.data;
                if(result.code == 1){
                    ElMessage.success('修改成功');
                    state.dialogVisible = false;
                    pageChange();
                }else{
                    ElMessage.error('修改失败');
                }
            })
        }

        pageChange();
        getGradeAndM();
        return {
            ...toRefs(state),
            pageChange,
            openAddDialog,
            submitForm,
            handleBatchExcelUpload,
            addstudent,
            editstudent,
            add,
            openBatchAddDialog,
            addlist,
            updateStu
        };
    }
};
</script>
<style scoped>
/* 使用与员工管理页面相同的样式 */
.header {
    margin-bottom: 20px;
}

.content-container {
    flex: 1;
    padding: 20px;
    overflow: auto;
}

.main-content {
    margin-left: 220px;
    margin-top: 60px;
    width: calc(100% - 220px);
    height: calc(100vh - 60px);
    overflow: auto;
}

.content-container {
    padding: 20px;
    min-height: calc(100% - 40px);
}

.main-container {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    display: flex;
}

.sidebar {
    width: 220px;
    background-color: #545c64;
    color: white;
    height: 100vh;
    position: fixed;
    left: 0;
    overflow-y: auto;
}

.logo {
    text-align: center;
    padding: 20px 0;
    color: #fff;
    margin: 0;
}

.nav-menu {
    border-right: none;
}

.top-bar {
    height: 60px;
    background-color: #fff;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 20px;
    position: fixed;
    top: 0;
    right: 0;
    left: 220px;
    /* 与侧边栏宽度一致 */
    z-index: 100;
}

.left-section {
    display: flex;
    align-items: center;
}

.welcome-text {
    font-size: 18px;
    font-weight: bold;
    color: #333;
}

.right-section {
    display: flex;
    align-items: center;
}

.user-info {
    display: flex;
    align-items: center;
    cursor: pointer;
}

.username {
    margin-left: 10px;
    font-size: 14px;
}

.student-detail-expand {
    padding: 20px;
    background-color: #f8f9fa;
}

.student-detail-expand :deep(.el-descriptions) {
    padding: 10px;
    margin: 0 20px;
}

.student-detail-expand :deep(.el-descriptions__header) {
    margin-bottom: 15px;
}

.student-detail-expand :deep(.el-descriptions__label) {
    width: 120px;
    color: #606266;
    font-weight: bold;
}

.student-detail-expand :deep(.el-descriptions__content) {
    color: #333;
}

.pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
    padding: 10px 0;
}

.pagination {
    margin-right: 20px;
}
</style>
